<template>
	<common-card type="form" title="填写课题成果" :loading="loading">
		<el-form ref="form" size="medium" :model="formData" :rules="formRules" :validate-on-rule-change="false">
			<el-form-item label="所属课题" prop="topicId">
				<el-select v-model="formData.topicId" placeholder="选择课题名称" style="width: 100%">
					<el-option v-for="(item, index) in topicData" :key="index" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="!!formData.topicId">
				<topic-info :data="checkedData"></topic-info>
			</el-form-item>
			<el-form-item prop="journals">
				<achievement-form ref="journal" page="add" type="1" title="期刊论文" v-model="formData.journals"></achievement-form>
			</el-form-item>
			<el-form-item prop="patents">
				<achievement-form ref="patent" page="add" type="2" title="授权专利" v-model="formData.patents"></achievement-form>
			</el-form-item>
			<el-form-item prop="meetings">
				<achievement-form ref="meeting" page="add" type="3" title="会议论文" v-model="formData.meetings"></achievement-form>
			</el-form-item>
			<el-form-item prop="awards">
				<achievement-form ref="awards" page="add" type="4" title="获得奖项" v-model="formData.awards"></achievement-form>
			</el-form-item>
		</el-form>
		<template slot="button">
			<el-button type="success" icon="sw-icon-btn-save" :loading="saveLoading" @click="handleSaveData()">保存</el-button>
			<el-button type="warning" icon="sw-icon-btn-share" :loading="submitLoading" :disabled="btnDisabled" @click="handleSubmitData()">提交</el-button>
		</template>
	</common-card>
</template>

<script>
import topicInfo from '../topicInfo';
import commonCard from '../commonCard';
import achievementForm from './achievement';
import { batchAddedMarvel } from '@/api/business/tbMarvel';
import { queryUserPageList, queryPageList, queryAuditPageList } from '@/api/business/tbTopic';
export default {
	components: { commonCard, topicInfo, achievementForm },
	props: {
		userRole: { type: String, default: '' },
		dataType: { type: String, default: '' }
	},
	data() {
		return {
			loading: false,
			formData: {},
			formRules: {
				topicId: [{ required: true, message: '请选择课题', trigger: 'change' }]
			},
			topicData: [],
			saveLoading: false,
			submitLoading: false
		};
	},
	computed: {
		topicId() {
			return this.$route.query.topicid || '';
		},
		topicListRequest() {
			if (this.userRole === 'manager') {
				return queryPageList;
			} else if (this.userRole === 'principal') {
				return queryAuditPageList;
			} else if (this.userRole === 'member') {
				return queryUserPageList;
			}
		},
		checkedData() {
			return this.topicData.find((n) => n.id === this.formData.topicId);
		}
	},
	watch: {
		topicId: {
			async handler(val) {
				this.loading = true;
				this.btnDisabled = false;
				await this.getTopicAuditData();
				this.loading = false;
				if (!val) return false;
				this.$set(this.formData, 'topicId', val);
			},
			immediate: true
		}
	},
	methods: {
		//获取课题数据
		async getTopicAuditData() {
			let params = { page: 1, limit: 9999, audit: '1' };
			let result = await this.topicListRequest(params).then((res) => res.data);
			if (result.code === '0') {
				this.topicData = result.data || [];
			}
		},

		//保存数据
		handleSaveData() {
			this.$refs['form'].validateField('topicId', (err) => {
				if (!!err) return false;
				this.saveLoading = true;
				this.$set(this.formData, 'isSave', '2');
				this.submitFormRequest();
			});
		},

		//提交数据
		handleSubmitData() {
			this.$refs['form'].validate(async (valid) => {
				let isWrite = await this.judgeDataWrite();
				if (!valid || !isWrite) return false;
				this.submitLoading = true;
				this.$set(this.formData, 'isSave', '1');
				this.submitFormRequest();
			});
		},
		
		//判断成果是否填写
		async judgeDataWrite() {
			let returnStatus = [];
			let awards = this.formData.awards || [];
			let patents = this.formData.patents || [];
			let journals = this.formData.journals || [];
			let meetings = this.formData.meetings || [];
			let awardsFilter = this.formatAchievement(awards);
			let patentsFilter = this.formatAchievement(patents);
			let journalFilter = this.formatAchievement(journals);
			let meetingsFilter = this.formatAchievement(meetings);
			if (journalFilter.length > 0) {
				returnStatus.push(await this.$refs['journal'].validateForm());
			}
			if (patentsFilter.length > 0) {
				returnStatus.push(await this.$refs['patent'].validateForm());
			}
			if (meetingsFilter.length > 0) {
				returnStatus.push(await this.$refs['meeting'].validateForm());
			}
			if (awardsFilter.length > 0) {
				returnStatus.push(await this.$refs['awards'].validateForm());
			}
			return !returnStatus.some((n) => !n);
		},

		//格式化成果数据
		formatAchievement(arr) {
			if (!!arr && Array.isArray(arr) && arr.length > 0) {
				return arr.filter((n) => Object.values(n).some((k) => !!k));
			} else {
				return [];
			}
		},

		//格式化表单参数
		formatFormParams() {
			let dataArrs = [];
			let params = this.$lodash.cloneDeep(this.formData);
			let awards = this.formatAchievement(params.awards);
			let patents = this.formatAchievement(params.patents);
			let journals = this.formatAchievement(params.journals);
			let meetings = this.formatAchievement(params.meetings);
			if (awards.length > 0) {
				dataArrs = [...dataArrs, ...awards.map((n) => ({ ...n, filed10: '4' }))];
			}
			if (patents.length > 0) {
				dataArrs = [...dataArrs, ...patents.map((n) => ({ ...n, filed10: '2' }))];
			}
			if (journals.length > 0) {
				dataArrs = [...dataArrs, ...journals.map((n) => ({ ...n, filed10: '1' }))];
			}
			if (meetings.length > 0) {
				dataArrs = [...dataArrs, ...meetings.map((n) => ({ ...n, filed10: '3' }))];
			}
			return dataArrs.map((item) => {
				let obj = { ...item };
				obj['isSave'] = params.isSave;
				obj['topicId'] = params.topicId;
				obj['name'] = this.checkedData.name;
				obj['auditId'] = this.checkedData.auditId;
				return obj;
			});
		},

		//提交表单请求
		async submitFormRequest() {
			let params = this.formatFormParams();
			if (params.length === 0) {
				this.$showCustomMessage('warning', `请填写成果信息在保存或提交！`);
				this.saveLoading = false;
				this.submitLoading = false;
				return false;
			} else {
				let result = await batchAddedMarvel(params).then((res) => res.data);
				this.saveLoading = false;
				this.submitLoading = false;
				if (result.code === '0') {
					this.btnDisabled = true;
					this.$showCustomMessage('success', '批量填写成果成功！');
					this.$router.back();
				}
			}
		}
	}
};
</script>

<style lang="scss" scoped></style>